from django.db import transaction
from rest_framework import serializers

from ERP_5.utils.get_inventory import get_inventory_by_goods
from goods_info.models import GoodsModel, GoodsInventoryModel, AttachmentModel
from goods_info.serializer.attachment_serializer import AttachmentsSerializer
from goods_info.serializer.category_serializer import CategorySerializer
from goods_info.serializer.units_serializer import UnitsSerializer


class GoodsInventorySerializer(serializers.ModelSerializer):
    """
    货品库存信息的序列化器
    """
    class Meta:
        model = GoodsInventoryModel
        fields = '__all__'


class GoodsBaseSerializer(serializers.ModelSerializer):
    """
    商品货品的序列化器
    """

    # 商品对应的多个库存记录
    inventory_list = GoodsInventorySerializer(many=True, required=True)

    class Meta:
        model = GoodsModel
        fields = '__all__'

    def create(self, validated_data):
        # 添加货品, 把库存信息先拿出来
        inventory_list = validated_data.pop('inventory_list')
        with transaction.atomic():
            goods = GoodsModel.objects.create(**validated_data)
            for item in inventory_list:  # item是字典
                # item代表一条库存信息, # 新建时，当前库存=初始库存
                item['cur_inventory'] = item.get('init_inventory', 0)
                GoodsInventoryModel.objects.create(goods=goods, **item)
        return goods

    def update(self, instance, validated_data):
        item_list = validated_data.pop('inventory_list')
        for item in item_list:  # 遍历每条库存信息，并修改最高库存和最低库存
            GoodsInventoryModel.objects.filter(warehouse_name=item['warehouse_name'], goods_id=instance.id).update(
                lowest_inventory=item.get('lowest_inventory', 0), highest_inventory=item.get('highest_inventory', 0))
        goods = super(GoodsBaseSerializer, self).update(instance=instance, validated_data=validated_data)
        return goods


class GoodsGetSerializer(serializers.ModelSerializer):
    """
    商品查询的序列化器
    目标：
        1、把商品的单位——所有信息展示出来
        2、展示商品信息所属的商品类别——所有信息展示出来
        3、展示商品的所有附件图片——所有图片信息展示出来
        4、展示商品的所有仓库中的库存信息——总库存
    """

    units = UnitsSerializer(read_only=True)
    category = CategorySerializer(read_only=True)
    images_list = serializers.SerializerMethodField(read_only=True)
    # 当前货品的总库存
    cur_inventory = serializers.SerializerMethodField(read_only=True)


    class Meta:
        model = GoodsModel
        fields = '__all__'

    def get_images_list(self, obj):
        result = []  # 返回的列表， 列表里面是字典(每个字典就是一个附件)
        if obj.images_list:
            ids = obj.images_list.split(',')  # 按照逗号分割
            if ids:
                for _id in ids:
                    item = AttachmentModel.objects.get(id=_id)
                    ser = AttachmentsSerializer(instance=item)
                    result.append(ser.data)

        return result


    def get_cur_inventory(self, obj):
        # 获取一个商品的总库存
        return get_inventory_by_goods(obj.id)